#include "Sock.hpp"
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

void Usage(std::string proc){
    std::cout << "Usage " << proc << " port " << std::endl; 
}

void* HandlerHttpRequest(void* args){
    int sock = *(int*)args;
    delete (int*)args;
    
    pthread_detach(pthread_self());
#define SIZE 1024 * 10
    char buffer[SIZE];
    memset(buffer, 0, SIZE);
    ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
    if (s > 0){
        buffer[s] = 0;
        std::cout << buffer << std::endl;                 //查看浏览器发来的HTTP请求
        //构建HTTP响应
        // std::string http_response = "http/1.0 200 OK\n";  //构建响应状态行
        // http_response += "Content-Type: text/plain\n";    //正文的属性
        // http_response += "\n";                            //空行
        // http_response += "hello net!";                    //正文  

        std::string html_file = WWWROOT;
        html_file += HOME_PAGE;
        // 返回的时候不仅仅是返回正文网页信息，而是要包括http请求
        std::string http_response = "http/1.0 200 OK\n";
        // 正文部分的数据类型
        http_response += "Content-Type: text/html; charset=utf8\n";
        struct stat st;
        stat(html_file.c_str(), &st);
        http_response += "Content-Length: ";
        http_response += std::to_string(st.st_size);
        http_response += "\n";
        //Set-Cookie: 服务器向浏览器设置一个cookie
        http_response += "Set-Cookie: id=1111111111\n"; 
        http_response += "Set-Cookie: password=2222\n"; 
        http_response += "\n";
        //std::cout << http_response << std::endl;
        //响应正文
        std::ifstream in(html_file);
        if (!in.is_open()){
            std::cerr << "open html error!" << std::endl;
        }
        else {
            std::cout << "open success" << std::endl;
            std::string content;
            std::string line;
            while (std::getline(in, line)){
                content += line;
            }
            //std::cout << content << std::endl;
            http_response += content;
            //std::cout << http_response << std::endl;
        }
        std::cout << http_response << std::endl;
        send(sock, http_response.c_str(), http_response.size(), 0);
    }
    close(sock);
    return nullptr;
}
int main(int argc, char* argv[]){
    if (argc != 2) { Usage(argv[0]); return 1;}
    uint16_t port = atoi(argv[1]);
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    for ( ; ; ){
        int sock = Sock::Accept(listen_sock);
        if (sock > 0){
            pthread_t tid;
            int *psock = new int(sock);
            pthread_create(&tid, nullptr, HandlerHttpRequest, (void*)psock);
        }
    }
}

